package com.green.javagreen.service;


import com.green.javagreen.bean.UserBean;
import com.green.javagreen.util.ExampleUtil;
import com.green.javagreen.util.IntegerUtil;
import com.green.javagreen.util.UpdateTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

/**
 * email:brioal@foxmail.com
 * github:https://github.com/Brioal
 */
@Service
public class UserServiceImpl implements UserService {
    private UserRepository userRepository;

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserBean save(UserBean bean) {
        UserBean exitBean = get(bean.getId());
        if (exitBean == null) {
            exitBean = bean;
        } else {
            UpdateTool.copyNullProperties(bean, exitBean);
        }
        userRepository.save(exitBean);
        return exitBean;
    }

    @Override
    public UserBean get(Integer id) {
        if (IntegerUtil.isNotValid(id)) {
            return null;
        }
        return userRepository.findById(id).orElse(null);
    }

    @Override
    public UserBean get(UserBean bean) {
        return userRepository.findOne(ExampleUtil.getSimpleExample(bean)).orElse(null);
    }

    @Override
    public Page<UserBean> find(UserBean bean) {
        return userRepository.findAll(ExampleUtil.getSimpleExample(bean), bean.getPageRequest());
    }

    @Override
    public void delete(Integer id) {
        if (IntegerUtil.isNotValid(id)) {
            return;
        }
        userRepository.deleteById(id);
    }

}
